"""
模块功能: 日志函数
"""
from datetime import datetime
import logging
import os
# import enum
# import sys
# from logging import handlers


def setup_logger(caller_file_name):
    # 1、创建一个logger
    logger_tmp = logging.getLogger('mylogger')
    logger_tmp.setLevel(logging.DEBUG)

    # 2、创建一个handler，用于写入日志文件
    log_folder = os.path.abspath('logs')  # 使用绝对路径
    # 检查日志目录是否存在，如果不存在则创建它
    if not os.path.exists(log_folder):
        os.makedirs(log_folder)
        # print(f'Created log folder: {log_folder}')

    # 生成日志文件名
    log_file_name = f'{os.path.splitext(os.path.basename(caller_file_name))[0]}-{datetime.now().strftime("%Y-%m-%d-%H-%M-%S")}.log'
    log_path = os.path.join(log_folder, log_file_name)
    # print(f'Log file will be saved to: {log_path}')
    # print(f'Current working directory: {os.getcwd()}')  # 输出当前工作目录

    # 创建文件处理器
    fh = logging.FileHandler(log_path)
    fh.setLevel(logging.DEBUG)

    # 再创建一个handler，用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # 3、定义handler的输出格式（formatter）
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

    # 4、给handler添加formatter
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # 5、给logger添加handler
    logger_tmp.addHandler(fh)
    logger_tmp.addHandler(ch)

    return logger_tmp


if __name__ == "__main__":
    logger = setup_logger(__file__)
    logger.info("This is an info message")
